<template>
  <div class="form-config">
    <el-form ref="formRef" label-width="100px">
      <el-form-item label="关联表单">
        <div class="form-list">
          <el-table :data="selectedForms" style="width: 100%">
            <el-table-column prop="name" label="表单名称" />
            <el-table-column label="表单OID" width="160">
              <template #default="{ row }">
                {{ row._id || row.id }}
              </template>
            </el-table-column>
            <el-table-column prop="type" label="类型" width="100">
              <template #default="{ row }">
                {{ getFormTypeText(row.type) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ $index }">
                <el-button link type="primary" @click="moveForm($index, $index - 1)" :disabled="$index === 0">
                  上移
                </el-button>
                <el-button link type="primary" @click="moveForm($index, $index + 1)" :disabled="$index === selectedForms.length - 1">
                  下移
                </el-button>
                <el-button link type="danger" @click="removeForm($index)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="form-selector">
            <el-select
              v-model="selectedFormId"
              placeholder="请选择要添加的表单"
              style="width: 300px"
              filterable
            >
              <el-option
                v-for="form in availableForms"
                :key="form.id"
                :label="form.name"
                :value="form.id"
              />
            </el-select>
            <el-button type="primary" @click="addForm" :disabled="!selectedFormId">
              添加表单
            </el-button>
          </div>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useFormStore } from '@/stores/form'

const props = defineProps({
  sectionId: {
    type: [String, Number],
    required: true
  }
})

const emit = defineEmits(['close'])

const formStore = useFormStore()
const selectedForms = ref([])
const availableForms = ref([])
const selectedFormId = ref('')

// 获取所有表单
const fetchForms = async () => {
  try {
    const allForms = await formStore.fetchForms()
    // 过滤掉已选择的表单
    updateAvailableForms(allForms)
  } catch (error) {
    ElMessage.error('获取表单列表失败')
  }
}

// 获取章节关联的表单
const fetchSectionForms = async () => {
  try {
    const forms = await formStore.fetchSectionForms(props.sectionId)
    selectedForms.value = forms
    updateAvailableForms(await formStore.fetchForms())
  } catch (error) {
    ElMessage.error('获取章节表单失败')
  }
}

// 更新可选表单列表
const updateAvailableForms = (allForms) => {
  const selectedIds = new Set(selectedForms.value.map(f => f.id))
  availableForms.value = allForms.filter(f => !selectedIds.has(f.id))
}

// 添加表单
const addForm = () => {
  const form = availableForms.value.find(f => f.id === selectedFormId.value)
  if (form) {
    selectedForms.value.push(form)
    updateAvailableForms(availableForms.value.concat(selectedForms.value))
    selectedFormId.value = ''
  }
}

// 移除表单
const removeForm = (index) => {
  const [removedForm] = selectedForms.value.splice(index, 1)
  availableForms.value.push(removedForm)
  availableForms.value.sort((a, b) => a.name.localeCompare(b.name))
}

// 移动表单
const moveForm = (fromIndex, toIndex) => {
  if (toIndex < 0 || toIndex >= selectedForms.value.length) return
  const forms = selectedForms.value
  const [movedForm] = forms.splice(fromIndex, 1)
  forms.splice(toIndex, 0, movedForm)
}

// 获取表单类型文本
const getFormTypeText = (type) => {
  const map = {
    basic: '基础表单',
    complex: '复杂表单',
    nested: '嵌套表单'
  }
  return map[type] || type
}

// 确认
const handleConfirm = () => {
  emit('close', selectedForms.value.map((form, index) => ({
    formId: form.id,
    order: index + 1
  })))
}

// 取消
const handleCancel = () => {
  emit('close')
}

onMounted(() => {
  fetchForms()
  fetchSectionForms()
})
</script>

<style scoped>
.form-config {
  padding: 20px 40px;
}

.form-list {
  margin-bottom: 20px;
}

.form-selector {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}
</style> 